#!/usr/bin/python
import os, sys, time, datetime, readline

# prepare for histfile usage
import os
histfile = os.path.join(os.environ["HOME"], ".zeitanalyse.pyhist")
try:
    readline.read_history_file(histfile)
except IOError:
    pass
import atexit
atexit.register(readline.write_history_file, histfile)

def parse(line):
    t = datetime.datetime.now()

    # split first item from line
    try:
	ts, line = line.split(" ", 1)
    except ValueError:
	return t, line
    # try to parse as hh:mm
    try:
	tt = datetime.datetime.strptime(ts, "%H:%M")
	t = datetime.datetime.combine(t.date(), tt.time())
	return t, line
    except ValueError, e:
	pass
    # try to parse as hh:mm:ss
    try:
	tt = datetime.datetime.strptime(ts, "%H:%M:%S")
	t = datetime.datetime.combine(t.date(), tt.time())
	return t, line
    except ValueError, e:
	pass
    # try to parse as -mm
    try:
	tt = datetime.datetime.strptime(ts, "-%M")
	ref = datetime.datetime.strptime("0", "%S")
	t = datetime.datetime.now() - (tt - ref)
	return t, line
    except ValueError, e:
	pass
    # try to parse as -hh:mm
    try:
	tt = datetime.datetime.strptime(ts, "-%H:%M")
	ref = datetime.datetime.strptime("0", "%S")
	t = datetime.datetime.now() - (tt - ref)
	return t, line
    except ValueError, e:
	pass
    # try to parse as -hh:mm:ss
    try:
	tt = datetime.datetime.strptime(ts, "-%H:%M:%S")
	ref = datetime.datetime.strptime("0", "%S")
	t = datetime.datetime.now() - (tt - ref)
	return t, line
    except ValueError, e:
	pass
	
    # if all parse attemps failed, recombine the line and return it
    line = ts + " " + line
    return t, line


logfile = open(os.path.expanduser("~/zeitanalyse.log"), "a")
print >> logfile, "= "*40
try:
    t_start, line_old = datetime.datetime.now(), ""
    while True:
        line = raw_input("> ")
	t_stop, line = parse(line)
	if line == "":
            print t_start.strftime("%Y-%m-%d %H:%M:%S"), "(%s)"%(t_stop - t_start), line_old
	    continue
	if line_old != "":
            print >> logfile, t_start.strftime("%Y-%m-%d %H:%M:%S"), "(%s)"%(t_stop - t_start), line_old
        logfile.flush()
	t_start, line_old = t_stop, line
except KeyboardInterrupt:
    pass
except EOFError:
    pass
print 

if line_old != "":
    print >> logfile, t_start.strftime("%Y-%m-%d %H:%M:%S"), "(%s)"%(datetime.datetime.now() - t_start), line_old
logfile.close()


